package com.wutianyi.module.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Text;
import com.wutianyi.module.commons.PropertyGroup;
import com.wutianyi.module.dao.PropertyGroupDao;
import com.wutianyi.utils.Utils;

import static com.wutianyi.entity.DataStoreField.DS_P_VALUE;
import static com.wutianyi.entity.EntityTypeEnum.PropertyGroup;
import static com.wutianyi.entity.DataStoreField.DS_P_CID;

/**
 * @author hanjiewu
 * 
 */
public class PropertyGroupDaoDataStoreImpl implements PropertyGroupDao {
	
	private static DatastoreService datastoreService = DatastoreServiceFactory
			.getDatastoreService();
	
	private void setEntity(PropertyGroup pg) {
		int id = pg.getId() != 0 ? pg.getId() : pg.hashCode();
		pg.setGmtModified(new Date());
		Entity entity = new Entity(PropertyGroup.name(), id);
		entity.setProperty(DS_P_CID, pg.getcId());
		entity.setProperty(DS_P_VALUE, new Text(Utils.serialize(pg)));
		datastoreService.put(entity);
		pg.setId(id);
	}
	
	@Override
	public void insertPropertyGroup(PropertyGroup pg) {
		pg.setId(0);
		setEntity(pg);
	}
	
	@Override
	public int updatePropertyGroup(PropertyGroup pg) {
		if (pg.getId() == 0) {
			return 0;
		}
		setEntity(pg);
		return 1;
	}
	
	@Override
	public List<PropertyGroup> listPropertyGroupsByPId(String parentId) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void insertPropertyGroups(List<PropertyGroup> propertyGroups) {
		if (CollectionUtils.isEmpty(propertyGroups)) {
			return;
		}
		int order = 1;
		for (PropertyGroup pg : propertyGroups) {
			pg.setOrder(order);
			insertPropertyGroup(pg);
			++order;
		}
	}
	
	@Override
	public List<PropertyGroup> listPropertyGroupsByCId(int cId) {
		Query query = new Query(PropertyGroup.name());
		query.addFilter(DS_P_CID, FilterOperator.EQUAL, cId);
		
		List<PropertyGroup> pgs = new ArrayList<PropertyGroup>();
		
		Iterable<Entity> iters = datastoreService.prepare(query).asIterable();
		
		for (Entity entity : iters) {
			PropertyGroup pg = (PropertyGroup) Utils.unSerialize(entity.getProperty(DS_P_VALUE));
			pg.setId((int) entity.getKey().getId());
			pgs.add(pg);
		}
		
		return pgs;
	}
	
}
